package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //Shop shop=queryWithPassThrough(id);
        //用互斥锁解决缓存击穿
        //Shop shop=queryWithMutex(id);

        //使用逻辑过期
        Shop shop = queryWithLogicalExpire(id);
        return Result.ok(shop);
    }

    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    public Shop queryWithLogicalExpire(Long id){
        //1.从redis查询缓存
        String key=CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isBlank(shopJson)){//因为空缓存对象不会into
            //3.不存在，直接返回null
            return null;
        }
        //4.存在命中，先把shop取出来，
        RedisData redisData = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(key), RedisData.class);
        Shop shop= JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //5.看一看过期时间
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.1未过期，直接返回旧值
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }
        //5.2已经过期，进行缓存重建

        //6.缓存重建

        //6.1获取互斥锁
        String lockKey="lock:shop"+id;
        boolean isLock = tryLock(lockKey);
        //6.3未拿到，返回旧值
        if(!isLock){
            return shop;
        }
        //6.2拿到互斥锁成功
        //6.3再次检查缓存是否过期，做DoubleCheck
        redisData = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(key), RedisData.class);
        expireTime = redisData.getExpireTime();
        //未过期，直接返回旧值
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }

        //任然过期，开启线程执行缓存重建
        CACHE_REBUILD_EXECUTOR.submit(()->{
            try {
                saveShop2Redis(id,20L);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                //释放锁
                unlock(lockKey);
            }
        });
        //任然返回旧值
        return shop;
    }

    public Shop queryWithMutex(Long id){
        //1.从redis查询缓存
        String key=CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopJson)){//因为空缓存对象不会into
            //3.存在，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //所以还需要判断是不是空值
        if(shopJson!=null){
            //返回错误信息
            return null;
        }

        //4.实现缓存重建
        //4.1获取互斥锁
        String lockKey="lock:shop"+id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //4.2判断是否获取锁成功
            if(!isLock){
                //4.3失败，休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }


            //4.4获取锁成功，根据id再次查询缓存，做二次检查，避免....，如果存在就不需要重建了
            shopJson = stringRedisTemplate.opsForValue().get(key);
            //2.判断是否存在
            if(StrUtil.isNotBlank(shopJson)){//因为空缓存对象不会into
                //3.存在，直接返回
                return JSONUtil.toBean(shopJson, Shop.class);
            }
            //4.5确实还是没有缓存，查询数据库

            shop = getById(id);
            //模拟缓存重建延迟
            //Thread.sleep(200);
            //5.还是不存在，返回错误
            if(shop==null){
                //防止缓存穿透，将空值写入redis
                stringRedisTemplate.opsForValue().set(key,"", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6.存在，写入redis
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //7.释放锁
            unlock(lockKey);
        }
        //8.返回
        return shop;
    }
    public Shop queryWithPassThrough(Long id){
        //1.从redis查询缓存
        String key=CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopJson)){//因为空缓存对象不会into
            //3.存在，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //所以还需要判断是不是空值
        if(shopJson!=null){
            //返回错误信息
            return null;
        }
        //4.不存在，去查询数据库，根据id
        Shop shop = getById(id);
        //5.还是不存在，返回错误
        if(shop==null){
            //防止缓存穿透，将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.存在，写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //7.返回
        return shop;
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }


    public void saveShop2Redis(Long id,Long expireSeconds){
        //1.查询店铺
        Shop shop = getById(id);
        /*
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        */
        //2.分装逻辑过期
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }
    @Override
    @Transactional //添加事务
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺Id不能为空");
        }
        //1.先更新数据库
        updateById(shop);
        //2.再删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
